#!/bin/sh
print_error () {
  local ERROR_MESSAGE="$1"
  local ERROR_CODE="$2"

  echo "$ERROR_MESSAGE" 1>&2

   if [ $ERROR_CODE ]
   then
      EXIT_CODE=$ERROR_CODE
   else
      EXIT_CODE=1
   fi
}

ERROR_WRAPPER_OPENED=false
print_error_wrapper () {
  if $ERROR_WRAPPER_OPENED;
  then
    ERROR_WRAPPER_OPENED=false
    print_error "-----------------------------------------------------------------------------"
    print_error ""
  else
    print_error ""
    print_error "------------------------------------------------------------------------------"
    print_error "                                 ERROR OCCURRED                               "
    ERROR_WRAPPER_OPENED=true
  fi
}

EXIT_CODE="0"

REPOS="$1"
TXN="$2"
PHP="php5"
SVNLOOK="svnlook"

FILES=`$SVNLOOK changed -t "$TXN" "$REPOS" | grep -E '^(U|A)' | awk '{print $2}' | grep .php$`
##
 # Checking the log message
 ##
LOG_MESSAGE=`$SVNLOOK log -t "$TXN" "$REPOS"`

if [ "$LOG_MESSAGE" = "" ]
then
   print_error "Please input your log message"
   EXIT_CODE=2
fi

for FILE in $FILES
  do

   TMP_DIR=`mktemp -d`
   TMP_FILENAME=`basename "$FILE"`
   TMP_FILE="$TMP_DIR/$TMP_FILENAME"

   `$SVNLOOK cat -t "$TXN" "$REPOS" "$FILE" > $TMP_FILE`

   ##
    # PHP Syntax Error Check
    #
    # Partial Idea From
    # http://pookey.co.uk/wordpress/archives/34-automatically-syntax-checking-of-php-files-when-checking-to-svn
    # http://svn.apache.org/repos/asf/subversion/trunk/contrib/hook-scripts/syntax-check.sh
    ##
   SYNTAX_ERROR=`$PHP -l -f $TMP_FILE 2>&1`
   SYNTAX_CHECK=$?
   if [ $SYNTAX_CHECK -ne 0 ]
   then
      print_error_wrapper
      print_error "Syntax Error#$SYNTAX_CHECK: $FILE"
      print_error "\r\n\r\n'$SYNTAX_ERROR'\r\n\r\n"
      if [ "$SYNTAX_OUTPUT" != "" ]
      then
         print_error "'$SYNTAX_OUTPUT'"
      fi
      print_error_wrapper
      EXIT_CODE=3
   fi
    # PHPDOC Checking

    PHPDOC_ERROR=`phpdoc --force -f "$TMP_FILE" -t "$TMP_DIR/docs" | grep "$TMP_FILE" -A20 | grep "Storing structure" -B20 | grep "  " | grep -vE "No page\-level DocBlock was found in file .*\.class\.php"`

   if [ "$PHPDOC_ERROR" != "" ]
   then
      print_error_wrapper
      print_error "Documentation Error For: $FILE"
      print_error "$PHPDOC_ERROR"
      print_error_wrapper
      EXIT_CODE=4
   fi
done
exit $EXIT_CODE
